#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   mac.py
@Time    :   2024-05-05 13:31
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   faith01238@hotmail.com
@Homepage : https://liumou.site
@Desc    :   设置Mac静态地址
"""

import subprocess
from argparse import ArgumentParser
from sys import exit
from os import system


def set_mac_address(eth, mac):
	"""
	设置Linux网络接口的MAC地址

	参数:
	eth -- 要设置MAC地址的网络接口名（如'eth0'）
	mac -- 新的MAC地址，格式为'XX:XX:XX:XX:XX:XX'
	"""
	# 使用ip命令设置MAC地址
	# 注意：这可能需要root权限或sudo
	command = f"ip link set {eth} address {mac}"
	try:
		subprocess.run(command, shell=True, check=True)
		print(f"MAC地址已成功设置为: {mac}")
	except subprocess.CalledProcessError as e:
		print(f"设置MAC地址时发生错误: {e}")
	txt = f"#!/bin/bash\nip link set {eth} address {mac}\nsystemctl restart networking\n"
	try:
		with open(file='/usr/bin/com.liumou.mac', mode='w', encoding='utf8') as w:
			w.write(txt)
	except Exception as e:
		print(f"写入文件时发生错误: {e}")
		exit(1)
	system("chmod 0777 /usr/bin/com.liumou.mac")


def get_mac_address_for_interface(interface_name):
	"""
	获取Linux网络接口的MAC地址
	:param interface_name:
	:return:
	"""
	cmd = "ip address show %s | grep link| awk '{print $2}'" % interface_name
	res = subprocess.getstatusoutput(cmd)
	if res[0] == 0:
		return res[1]
	else:
		return None


def service():
	txt = """[Unit]
Description=This is a static MAC configuration service script
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/com.liumou.mac
StandardOutput=journal
KillMode=control-group
Restart=on-failure
RestartPreventExitStatus=255
StandardError=inherit
SyslogIdentifier=com.liumou.mac

[Install]
WantedBy=multi-user.target
Alias=com.liumou.mac.service
"""
	try:
		with open(file='/etc/systemd/system/com.liumou.mac.service', mode='w', encoding='utf8') as w:
			w.write(txt)
	except Exception as e:
		print(f"写入文件时发生错误: {e}")
		exit(1)
	system("systemctl daemon-reload")
	system("systemctl enable com.liumou.mac.service")
	system("systemctl start com.liumou.mac.service")


if __name__ == "__main__":
	arg = ArgumentParser(description='当前脚本版本: 1.0', prog="Linux网卡Mac地址设置脚本")
	arg.add_argument('-i', '--eth', type=str, help="设置网络接口", default="eth0", required=False)
	arg.add_argument('-m', '--mac', type=str, help="设置Mac地址", default=None, required=False)
	args = arg.parse_args()
	interface = args.interface
	args_mac = args.mac
	if args_mac is None:
		args_mac = get_mac_address_for_interface(interface)
	# 示例：设置eth0接口的MAC地址
	if args_mac is None:
		exit(2)
	else:
		set_mac_address(interface, args_mac)
		service()
